package cn.xieyang.gen.database.mysql;

import cn.xieyang.gen.config.DBConfig;
import cn.xieyang.gen.handler.DBConfigHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
public class ImportSql {

    public static void doImport(String sqlFilePath) throws SQLException, ClassNotFoundException, FileNotFoundException {
        // 数据库连接
        Connection conn = DBConfigHandler.getConn(DBConfig.builder()
                // 地址
                .url("jdbc:mysql://192.168.196.7:3306/ganjiang-db")
                // 用户名
                .userName("root")
                // 密码
                .password("123456")
                .build());
        // 在建立连接后添加：
        ScriptRunner runner = new ScriptRunner(conn);
        runner.setLogWriter(null); // 禁用日志输出
        long start1 = System.currentTimeMillis();
        runner.runScript(new FileReader(sqlFilePath));
        log.info("耗时统计：新增数据耗时：{}", formatDuration(start1, System.currentTimeMillis()));
    }

    public static String formatDuration(long start, long end) {
        long totalMillis = end - start;

        long hours = totalMillis / 3600000;
        long remaining = totalMillis % 3600000;

        long minutes = remaining / 60000;
        remaining %= 60000;

        long seconds = remaining / 1000;
        long millis = remaining % 1000;

        return String.format("%d时%d分%d秒%d毫秒", hours, minutes, seconds, millis);
    }

}
